﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Models;

namespace Web
{
    public partial class admin_works : System.Web.UI.Page
    {
        private const int PAGESIZE = 8;
        private int PAGECOUNT;
        protected void Page_Load(object sender, EventArgs e)
        {
            int page = 1;
            int cid = 0;
            try
            {
                page = Int32.Parse(Request.QueryString["page"].ToString());
            }
            catch {
            }
            try{
                cid = Int32.Parse(Request.QueryString["cid"].ToString());
            }catch{}

            PAGECOUNT = WorksInfoLogic.GetPageCount(PAGESIZE,cid);

            if(!IsPostBack){
                BindData(cid, page);
            }
        }
        private void BindData(int cid,int page)
        {
            BindWorksInfoList(cid, page);
            BindPagerList(cid);
            BindPagerLink( page, cid);
            BindNotice();
        }
        private void BindWorksInfoList(int cid,int page )
        {
            List<WorksInfo> list = WorksInfoLogic.GetWorksInfo(cid, PAGESIZE, page);
            //foreach(var item in list )
            //{
            //    item.CategoryName = WorksCategoryInfoLogic.GetOneWorksInfo(item.CategoryID).CategoryName;
            //}
            for (int i = 0; i < list.Count; i++)
            {
                list[i].CategoryName = WorksCategoryInfoLogic.GetOneWorksInfo(list[i].CategoryID).CategoryName;
                list[i].ShowID = i + 1 + (page - 1) * PAGESIZE;
            }
            ListRpt.DataSource = list;
            ListRpt.DataBind();
        }
        private void BindPagerList(int cid)
        {
            List<string> page = new List<string>();
            for (int i = 1; i <= PAGECOUNT; i++)
            {
                page.Add(i + "&cid=" + cid.ToString());
            }
            NewsListPage.DataSource = page;
            NewsListPage.DataBind();
        }
        private void BindPagerLink(int nowPage, int cid)
        {
            int nextPage = nowPage + 1 > PAGECOUNT ? PAGECOUNT : nowPage + 1;
            int prePage = nowPage - 1 > 0 ? nowPage - 1 : 1;

            hlFirst.NavigateUrl = "?page=1&cid=" + cid.ToString();
            hlLast.NavigateUrl = "?page=" + PAGECOUNT.ToString() + "&cid=" + cid.ToString();
            hlNext.NavigateUrl = "?page=" + nextPage.ToString() + "&cid=" + cid.ToString();
            hlPre.NavigateUrl = "?page=" + prePage.ToString() + "&cid=" + cid.ToString();
        }
        private void BindNotice()
        {
            noticesuccess.Visible = false;
            noticefailed.Visible = false;
        }
        private int InitFromUrl(string url, int first)
        {
            int rtn = first;
            try
            {
                rtn = Int32.Parse(Request.QueryString["page"].ToString());
            }
            catch
            {
                rtn = first;
            }
            return rtn;
        }
    
        protected void btnChange_Click(object sender, EventArgs e)
        {
            if (ddlChange.SelectedValue != "1")
            {
                return;
            }
            string[] strWorksId = Request.Form["ckb"].Split(',');
            int[] worksId = new int[strWorksId.Count()];
            try
            {
                for (int i = 0; i < strWorksId.Count(); i++)
                {
                    worksId[i] = Int32.Parse(strWorksId[i]);
                }
            }
            catch {
                return;
            }
            int count = 0;
            foreach (var id in worksId)
            {
                DeleteOldPic(id);
                count += WorksInfoLogic.DeleteWorksInfo(id);
            }
            if (count == strWorksId.Count())
            {
                ChangeStatus(true);
                int page = InitFromUrl("page", 1);
                int cid = InitFromUrl("cid",0);
                BindWorksInfoList(cid,page);
            }
            else
            {
                ChangeStatus(false);
            }

        }
        private void ChangeStatus(bool flag)
        {
            noticesuccess.Visible = flag ? true : false;
            noticefailed.Visible = flag ? false : true;
            ScriptManager.RegisterStartupScript(this, this.GetType(), "initclosenotice", "AjaxChange();", true);
        }
        private void DeleteOldPic(int worksID)
        {
            List<WorksPicInfo> piclist = WorksPicInfoLogic.GetAllWorksPicInfo(worksID);
            foreach (var pic in piclist)
            {
                string username = Session["UserName"] == null ? "null" : Session["UserName"].ToString();
                string tip = " UserName:" + username + " " + DateTime.Now.ToString() + " deleting WorksID:" + worksID + " PicURL:" + pic.PicURL + " ";
                try
                {
                    System.IO.File.Delete(Server.MapPath(pic.PicURL));
                    tip += " ok! ";
                }
                catch {
                    tip += " failed! ";
                }
                WriteLog(tip);
            }
        }
        private void WriteLog(string msg)
        {
            try
            {
                System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("~/log/workspic.txt"), System.IO.FileMode.Append, System.IO.FileAccess.Write);
                System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
                sw.WriteLine(msg);
                sw.Close();
            }
            catch { }
        }
        protected void ibtnDelete_OnClick(object sender, EventArgs e)
        {
            ImageButton ib = new ImageButton();
            int ID = 0;
            try
            {
                ib = (ImageButton)sender;
                ID = Int32.Parse(ib.ToolTip.ToString());
            }
            catch
            {
                return;
            }

            DeleteOldPic(ID);
           
            if (WorksInfoLogic.DeleteWorksInfo(ID) != 1)
            {
                ChangeStatus(false);
            }
            else
            {
                ChangeStatus(true);
                int page = InitFromUrl("page", 1);
                int cid = InitFromUrl("cid", 0);
                BindWorksInfoList(cid, page);
            }
        }
    }
}
